/* 

MAD.js is an in-house e-commerce javascript library
copyright 2009,2010 MAD Productions

version 1.3

*/
/*

*/


/*(function() {
    function async_load(){
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.src = 'http://api.treepodia.com/video/Treepodia.js';
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);
    }
    if (window.attachEvent)
        window.attachEvent('onload', async_load);
    else
        window.addEventListener('load', async_load, false);
})();
*/
var MAD = {};

//Core functions
MAD.core = (function() {
	
	//do a little browser test
//  var _browser = {
//		ie:(window.ActiveXObject) ? true : false
//	};
	
	//specify card image paths
	var _cardImgs = {
	    delta: "url(/common/images/checkout/delta.gif) no-repeat",
	    electron: "url(/common/images/checkout/electron.gif) no-repeat",
	    maestro: "url(/common/images/checkout/maestro.gif) no-repeat",
	    mastercard: "url(/common/images/checkout/mastercard.gif) no-repeat",
	    solo: "url(/common/images/checkout/solo.gif) no-repeat",
	    visa: "url(/common/images/checkout/visa.gif) no-repeat",
	    amex: "url(/common/images/checkout/amex.gif) no-repeat"
	};
	
	//specify popup sizes
//	var _popSizes = {
//		delivery:"500:417",
//		emailFriend:"488:510",
//		forgottenPassword:"500:360",
//		product:"620:700",
//		securityCode:"500:417",
//		terms:"620:600",
//		sizeGuide:"600:600"
//	};
	
	//jquery getElsByClass wrapper function	
//	var _getElementsByClass = function(className) {
//		return $("." + className);
//	};
	
	//attach events crossbrowser
//	var _xAttachEvent = function(el, evt, handler, args) {
//				
//		//is 1st arg a string or array?
//		if (typeof(el) == "string") {
//			
//			//work out if id or classname
//			if (el.indexOf(".") == -1) {
//			
//				//make array of single element to attach event listener to
//				var theEl = [];
//				theEl.push(document.getElementById(el));
//			} else {
//				
//				//get elements to attach event to
//				var theEl = _getElementsByClass(el.substr(1));
//			}
//			
//			if (theEl.length == 0) {
//			
//			  //if array empty do nothing
//			  return false
//			
//			} else { 
//			  for (var x = 0; x < theEl.length; x++) {
//					
//					//attach event listener to elements and pass args
//					(_browser.ie == true) ? theEl[x].attachEvent("on" + evt, function(e) { handler(e, args) }) : theEl[x].addEventListener(evt, function(e) { handler(e, args) }, false);
//				}
//			}	
//		
//		} else if (typeof(el) == "object") {
//			
//			//attach event to each element in array
//			for (var x = 0; x < el.length; x++) {
//				
//				//determine whether class name or id
//				if (el[x].indexOf(".") == -1) {
//				
//			  	var theEl = document.getElementById(el[x]);
//					(_browser.ie == true) ? theEl.attachEvent("on" + evt, handler) : theEl.addEventListener(evt, handler, false); 				
//				} else {
//					
//					var theEl = _getElementsByClass(el[x].substr(1));
//					for (var y = 0; y < theEl.length; y++) {
//						(_browser.ie == true) ? theEl[y].attachEvent("on" + evt, handler) : theEl[y].addEventListener(evt, handler, false); 
//					};
//				}
//			}
//		}
//	};
//	
//	//stop events cross-browser
//	function _stopIt(e) {
//		
//		//stop the event
//		(_browser.ie == true) ? stopIEevent() : stopFFevent() ;
//		
//		function stopIEevent() {
//			window.event.returnValue = false;
//			window.event.cancelBubble = true;
//		}
//		
//		function stopFFevent() {
//			
//			e.preventDefault();
//			e.stopPropagation();
//			return false;
//		}	
//	};
//	
//	//slide things
//	var _jSlide = function(e, args) {
//				
//		//get the id of the el to slide using handlerArgs obj
//		var slideEl = (args.id != null) ? document.getElementById(args.id) : null ;
//		
//		//get trigger el
//		var trigger = (args.linkID == null) ? (_browser.ie == true) ? e.srcElement.tagName.toLowerCase() : e.target.tagName.toLowerCase() : document.getElementById(args.linkID) ;
//		
//		if (trigger != "input") {
//			
//			//slide toggle the el
//			$(slideEl).slideToggle("slow", function() {
//							
//				//change open link to close link
//				($(trigger).children("strong").text().indexOf("Expand") != -1) ? $(trigger).children("strong").text("Collapse Basket") : $(trigger).children("strong").text("Expand Basket") ;
//				
//				//change class names on link
//				($(trigger).hasClass("expand") == true) ? $(trigger).addClass("collapse").removeClass("expand") : $(trigger).addClass("expand").removeClass("collapse");
//				
//				//add selected class to link if you want to
//				//trigger = (_browser.ie == true) ? e.srcElement : e.target;
////				
////				if ($(trigger).hasClass("selected") && args.applySelectedClass == true ) {
////					$(trigger).removeClass("selected").parent().removeClass("buttonSelected");
////				} else {
////					(args.applySelectedClass == true) ? $(trigger).addClass("selected").parent().addClass("buttonSelected") : null ;
////				}
//			});
//		} else {
//		
//			//remove boldness from all labels
//			$(trigger).parent().children().css({ color:"#C1C8CF" });
//			
//			//get actual clicked radio
//			trigger = (_browser.ie == true) ? e.srcElement : e.target ;
//			
//			//add boldness to label of radio that was clicked
//			$(trigger).parent().next().css({ color:"#2B2E38" });
//			
//			if ($(trigger).hasClass("same")) {
//				//if 'same' radio is selected and address already closed do nothing else shut address
//				($(slideEl).hasClass("closed")) ? null : $(slideEl).slideUp("slow").removeClass("open").addClass("closed") ;
//			} else {
//				//if 'diff' radio is selected and address already open do nothing, else open address
//				($(slideEl).hasClass("open")) ? null : $(slideEl).slideDown("slow").removeClass("closed").addClass("open") ;
//			}
//		}	
//		
//		_stopIt(e);
//	};
	
	//function to handle chaning credit card logo in checkout
	var _changeCard = function(e, args) {
				
		//get the id of the select box el from config obj
		var selectEl = (args.id != null) ? document.getElementById(args.id) : null ;
		
		//get the id of the span to hold the card image
		var imgEl = (args.imgId != null) ? document.getElementById(args.imgId) : null ;
		
		//get the selected card (jumping through hoops for IE)
		var cardIndex = selectEl.selectedIndex;
		var cardChoice = selectEl[cardIndex].text.toLowerCase();
		
		//remove image if first option selected
		(cardIndex == 0) ? imgEl.style.background = "none" : null ;
		
		//get path to image
		var imgPath = _cardImgs[cardChoice];
				
		//set bg image of span
		imgEl.style.background = imgPath;

};

	//bookmark
    var _bookmark = function(title, url) {
        if (window.sidebar) {
            window.sidebar.addPanel(title, url, "");
        } else if (document.all) {
            window.external.AddFavorite(url, title);
        } else if (window.opera && window.print) {
            return true;
        }
    };
	
	//open popup method
//	var _openPopup = function(e, args) {
//				
//		//remove target (target set in mark-up to make popups usable if JS switched off)
//		(_browser.ie == true) ? e.srcElement.setAttribute("target", "") : e.target.setAttribute("target", "") ;
//	  
//		var theLink = "";
//		
//		//is popup link wrapped round an image?
//		if (_browser.ie == true) {
//			theLink = (e.srcElement.tagName.toLowerCase() == "img" || e.srcElement.tagName.toLowerCase() == "strong") ? e.srcElement.parentNode : e.srcElement ;
//		} else {
//			theLink = (e.target.tagName.toLowerCase() == "img" || e.target.tagName.toLowerCase() == "strong") ? e.target.parentNode : e.target;
//		}
//		
//		//get popup URL
//		var href = theLink.href;
//		
//		//get popup filename
//		if (!args || args.popupName == "undefined" || args.popupName == null) {
//			
//			//work through string and count / characters
//			var slashCount = 0;
//			if (href.indexOf("/") != -1) {
//				for (var x = 0; x < href.length; x++) {
//					(href.charAt(x) == "/") ? slashCount++ : null ;
//				}
//			}
//			
//			var popName = href.split("/", slashCount + 1);
//			var thePopup = popName[popName.length -1].split(".")[0];
//					
//		} else {
//				
//			var thePopup = args.popupName;
//			
//		}
//		
//		//get dimensions from popSizes object
//		width = _popSizes[thePopup].split(":")[0];
//		height = _popSizes[thePopup].split(":")[1];
//		
//		//open the popup
//		window.open(href, null, 'scrollbars=yes,status=no,width='+width+',height='+height);
//		
//		//stop the event
//		_stopIt(e);
//		
//	};
//	
//	//close popup
//	var _closePopup = function(e) {
//		window.close();
//	};
//	
//	var _setFaqHeadingOn = function(e) {
//
//		//get the faq that was clicked
//		if (_browser.ie == true) {
//			var faqNumber = e.srcElement.href.split("#")[1];
//		} else {
//			var faqNumber = e.target.href.split("#")[1];
//		}
//		
//		//add on class to faq answer
//		$("#" + faqNumber).addClass("faqHeaderOn");
//		
//	};
//	
//	var _setFaqHeadingOff = function(e) {
//		
//		//remove faq on class
//		$(".faqHeaderOn").removeClass("faqHeaderOn");
//		
//	};
//	
//	var _printPage = function(e) {
//		window.print();
//	};
//	
//	//remove default word in inputs
//	var _inputClear = function(e, args) {
//		
//		//get the input
//		var theInput = (_browser.ie == true) ? e.srcElement : e.target;
//		
//		//remove default word
//		(theInput.value == args.displayWord) ? theInput.value = "" : null ;
//	};
//	
//	var _inputFill = function(e, args) {
//		
//		//get the input
//		var theInput = (_browser.ie == true) ? e.srcElement : e.target;
//		
//		//add the default word back on blur
//		(theInput.value == "") ? theInput.value = args.displayWord : null ;
//		
//	};
	
	//fix open/closed address boxes on post-back pages
	var _closeAddress = function() {
	    $(this).parent().find(".genericAddress").slideUp(700);
		$(".slideParentSame").children("div").addClass("existingOn").removeClass("existingOff");
		$(".slideParentDiff").children("div").addClass("existingOff").removeClass("existingOn");
	};
	
	var _openAddress = function() {
		$(this).parent().find(".genericAddress").slideDown(700);
		$(".slideParentSame").children("div").addClass("existingOff").removeClass("existingOn");
		$(".slideParentDiff").children("div").addClass("existingOn").removeClass("existingOff");
	};
	
	//change product image when thumbnail rolled over
//	var _imageOver = function(e) { 
//		var hook = (_browser.ie == true) ? e.srcElement : e.target;
//		if (hook.className == "nail n1") { $(".t1").css("zIndex","3"); $(".main .openImgPopup img").css("zIndex", "-1") } ; 
//		if (hook.className == "nail n2") { $(".t2").css("zIndex","3"); $(".main .openImgPopup img").css("zIndex", "-1") } ;
//		if (hook.className == "nail n3") { $(".t3").css("zIndex","3"); $(".main .openImgPopup img").css("zIndex", "-1") } ;
//	};
//	
//	//change it back
//	var _imageOut = function(e) {
//		var hook = (_browser.ie == true) ? e.srcElement : e.target;
//		if (hook.className == "nail n1") { $(".t1").css("zIndex","1"); $(".main .openImgPopup img").css("zIndex", "2") } ;
//		if (hook.className == "nail n2") { $(".t2").css("zIndex","1"); $(".main .openImgPopup img").css("zIndex", "2") } ;
//		if (hook.className == "nail n3") { $(".t3").css("zIndex","1"); $(".main .openImgPopup img").css("zIndex", "2") } ;
//	};
//
//  //emulate hover on li in IE6 with class
//	var _on = function(which) { 
//		$(which).addClass("ieHover");
//	}
//	
//	//remove class
//  var _off = function(which) { 
//		$(which).removeClass("ieHover");
//	}
	
	//return public methods
	return {
//		xAttachEvent: _xAttachEvent,
		changeCard: _changeCard,
		bookmark: _bookmark
//		openPopup: _openPopup,
//		closePopup: _closePopup,
//		jSlide: _jSlide,
//		setFaqHeadingOn: _setFaqHeadingOn,
//		setFaqHeadingOff: _setFaqHeadingOff,
//		inputClear: _inputClear,
//		inputFill: _inputFill,
//		printPage: _printPage,
//		closeAddress: _closeAddress,
//		openAddress: _openAddress,
//		imageOver: _imageOver,
//		imageOut: _imageOut,
//		on: _on,
//		off: _off
	}
})();

MAD.lightBox = (function() {

    var _init = function() {
        $(".overlay").click(function() {
            if (!$(".modal").is(":visible")) {
                $(".lightbox").hide();
                $(".expandedContent").hide();
                $(this).hide();
            }
        });

        $(".lightbox .btn_close").attr('href', 'javascript:MAD.lightBox.hide();');
    }

    var _show = function(id) {
        $(id).css("top", ($(window).height() - $(id).height()) / 2 + $(window).scrollTop() + "px");
        $(id).css("left", ($(window).width() - $(id).width()) / 2 + $(window).scrollLeft() + "px");
        $('.overlay').show();
        $(id).show();
        return false;
    }

    var _hide = function() {
        $(".lightbox").hide();
        $(".overlay").hide();
        //return false;
    }

    //return public methods
    return {
        init: _init,
        show: _show,
        hide: _hide
    }
})();

MAD.treepodia = (function() {
    var _acc;
    var _accID;
    var _skus = [];
    var _vids;
    var _product;

    var _init = function(account) {
        _accID = account;
        _getAccount();
    }

    var _getAccount = function() {
        if (_acc === undefined) {
            _acc = Treepodia.getAccount(_accID);
        }
    }

    //    var _reinit = function() {
    //        _getAccount();
    //        var t = setTimeout(function() { _acc.requestVideos(_skus, _handleVideo); }, 500);
    //    }

    //    var _reinitCustom = function(handler) {
    //        _getAccount();
    //        var t = setTimeout(function() { _acc.requestVideos(_skus, handler); }, 500);
    //    }

    //    var _addSku = function(sku) {
    //        if (!_skus[sku]) {
    //            _skus.push(sku);
    //        }
    //    }

    //    var _handleVideo = function(o) {
    //        _vids = o;

    //        _showVideos();
    //    }

    //    var _hasVideo = function(sku) {
    //        if (!(_vids === undefined)) {
    //            var video
    //            try {
    //                video = _vids.getVideo(sku);
    //            }
    //            catch (e) { }
    //            return (video != null && video.hasVideos());
    //        }
    //        else {
    //            return false;
    //        }
    //    }

    //    var _showVideos = function() {
    //        elements = $('a.btn_playVideo');
    //        elements.each(function() {
    //            var sku = $(this).attr("sku");

    //            if (!(sku === undefined)) {
    //                var video
    //                try {
    //                    video = _vids.getVideo(sku);
    //                }
    //                catch (e) { }
    //                if (video != null && video.hasVideos()) {
    //                    //if (vids.contains($(this).attr("sku"))) {
    //                    $(this).css("display", "block");
    //                    $(this).attr('href', "javascript:MAD.treepodia.showLB('" + $(this).attr("sku") + "','" + $(this).parents('div').find('h3 a').attr("title") + "','" + $(this).parents('div').find('.btn_moreInfo').attr("href") + "');");
    //                }
    //            }
    //        });
    //    }

    var _showLB = function(Video, title, prodURL) {
        MAD.lightBox.show(".lbTreepodia");
        //$("#swfDiv").html('<embed height="351px" width="554px" flashvars="callback=_trpd_video_callback_0&amp;video=http://videos.treepodia.com/UA-OLG/' + Video + '-OnlineGolf1-olg1.d.flv&amp;auto-play=false&amp;backcolor=0xffffff&amp;frontcolor=0xCCCCCC&amp;lightcolor=0x557722&amp;allowfullscreen=false&amp;ShowLogo=1&amp;play_on_click=true&amp;init_mute=false" wmode="transparent" allowfullscreen="false" swliveconnect="true" allowscriptaccess="always" quality="high" bgcolor="ffffff" name="swfID_0" id="swfID_0" src="http://www.treepodia.com/video/treepodia_player.swf" type="application/x-shockwave-flash">');

        _getProductVideo(Video, function(videoController) {
            videoController.setAutoplay(true);
            videoController.setWidth(554);
            videoController.setHeight(351);
            videoController.setWmode('transparent');
            videoController.show('swfDiv');
        });

        $('.lbTreepodia').find('h3').html(title);

        if (prodURL.length > 0) {
            $('.lbTreepodia').find('a.btn_viewProductLarge').css("display", "block");
            $('.lbTreepodia').find('a.btn_viewProductLarge').attr('href', prodURL);
        }
        else {
            $('.lbTreepodia').find('a.btn_viewProductLarge').css("display", "none");
            $('.lbTreepodia').find('a.btn_viewProductLarge').attr('href', '');
        }

        $(".lbTreepodia a.btn_close").click(function() { MAD.treepodia.stopVideo(Video); });

        $(".overlay").click(function() {
            if (!$(".modal").is(":visible")) {
                $(".lightbox").hide();
                $(".expandedContent").hide();
                $(this).hide();
            }
            MAD.treepodia.stopVideo(Video);

            $(".overlay").click(function() {
                if (!$(".modal").is(":visible")) {
                    $(".lightbox").hide();
                    $(".expandedContent").hide();
                    $(this).hide();
                }
            });
        });
    }

    var _stopVideo = function(Video) {
        //_showLB(Video, title, '');
        _getProductVideo(Video, function(vc) {
            vc.setAutoplay(false);
            vc.setWidth(554);
            vc.setHeight(351);
            vc.setWmode('transparent');
            vc.show('swfDiv');
        });
    }

    var _playVideo = function(Video, title) {
        _showLB(Video, title, '');
    }

    var _getProduct = function(sku) {
        _product = Treepodia.getProduct(_accID, sku);
    }

    var _getProductVideo = function(sku, handler) {
        _getProduct(sku);
        _product.requestVideo(handler);
    }

    var _logAddBasket = function(sku) {
        //_product = Treepodia.getProduct(account, sku);
        if (_product === undefined) {
            _getProduct(sku);
        }
        _product.logAddToCart();
    }

    //return public methods
    return {
        init: _init,
        //        reinit: _reinit,
        //        reinitCustom: _reinitCustom,
        //        handleVideo: _handleVideo,
        //        showVideos: _showVideos,
        playVideo: _playVideo,
        //        hasVideo: _hasVideo,
        showLB: _showLB,
        stopVideo: _stopVideo,
        //        addSku: _addSku,
        //        skus: _skus,
        logAddBasket: _logAddBasket,
        getProductVideo: _getProductVideo
    }
})();

//Product Related Functions
MAD.products = (function() {
    var _Products = [];

    //Add product to collection
    var _addProduct = function(o) {
        _Products[o.id] = o;
    }

    //Finds a product in the array
    var _findProduct = function(i) {
        return _Products[i];
    }

    // LARGE PRODUCT IMAGE LIGHT BOX - (PRODUCT OBJECT)
    function enlargeProduct(i) {
        var enProd = i;
        $('.lbEnlargeProduct').find('img').attr('src', '');
        $('.lbEnlargeProduct').find('h3').html(enProd.brandName + ' ' + enProd.name);
        $('.lbEnlargeProduct').find('.commMsg').html(enProd.commercialMsg);
        $('.lbEnlargeProduct').find('img').attr('src', enProd.image);
        $('.lbEnlargeProduct').find('a.btn_viewProdDetails').attr('href', enProd.href);
        $(".lbEnlargeProduct").click(function() {
            MAD.lightBox.hide();
        });
        showLightBox('.lbEnlargeProduct');
    }

    //Displays the product with id i in the specified enlarged container
    var _showProduct = function(target, sender, i) {
        var link = $(sender).find('h3 a').attr('href');

        target = '#' + target;

        var aTitle = $(target + '_aTitle');
        aTitle.attr('href', link);
        $(target + '_aView').attr('href', link);
        $(target + '_imgProduct').parents('a').attr('href', link);
        var img = $(target + '_imgProduct');
        img.attr('src', $(sender).find('img').attr('src'));
        img.attr('width', $(sender).find('img').attr('width'));
        img.attr('height', $(sender).find('img').attr('height'));

        var o = _findProduct(i);

        // ENLARGE IMAGE FROM HOVER POPUP
        $(".magnify").click(function() {
            enlargeProduct(o);
            return false;
        });

        aTitle.html('<strong>' + o.brandName + '</strong> ' + o.name);
        aTitle.title = o.brandName + ' ' + o.name;

        if ($(sender).find('.image span').attr('class')) {
            $(target + '_Sash').attr('class', $(sender).find('.image span').attr('class'));
        }
        else {
            $(target + '_Sash').attr('class', '');
        }

        if ($(sender).find('.image span').css('background-image')) {
            $(target + '_Sash').css('background-image', $(sender).find('.image span').css('background-image'));
        }
        else {
            $(target + '_Sash').css('background-image', '');
        }

        $(target).find('.specialTag').remove();
        $(target).find('.newTag').remove();
        if ($(sender).find('.specialTag').attr('class')) {
            $(target).append('<div class="specialTag"></div>');
        }
        if ($(sender).find('.newTag').attr('class')) {
            $(target).append('<div class="newTag"></div>');
        }
        
        $(target + '_CommMsg').html(o.commercialMsg);

        //Rating needs moving so it changes the class
        //document.getElementById(target + "_Rating").innerHTML = o.rating;
	//	alert(o.price);
        if (o.price == "HIDE") {
            $(target + '_Price').html('<a href="' + o.href + '" title="Click for price">Click for price</a>');
            $(target + '_Save').html('');
            $(target + '_RRP').html('');
        }
		else if (o.price == "titleist") {
			$(target + '_Price').html('<a href="#"><strong></strong></a>');	
			$(target + '_Save').html('');
            $(target + '_RRP').html('');
		}
        else {
            $(target + '_Price').html('PRICE <strong>&pound;' + o.price + '</strong>');

            if (o.save > 0) {
                $(target + '_Save').html('SAVE <span>' + o.save + '%</span>');
                $(target + '_RRP').html('MRRP &pound;' + o.rrp);
            }
            else {
                $(target + '_Save').html('');
                $(target + '_RRP').html('');
            }
        }


        var aVideo = $(target + '_aVideo');
        if (!(o.video == 'NOVID')) {
            aVideo.attr('href', "javascript:MAD.treepodia.showLB('" + o.video + "','" + o.brandName + " " + o.name + "','" + o.href + "');");
            aVideo.css({ display: 'block' });
        }
        else {
            aVideo.css({ display: 'none' });
        }

        var divDeal = $(target + '_Deal');
		if (o.discount) {			
            if (o.discount.type == "GIFT") {
                if (o.discount.value == "100") {
                    //free gift
                    divDeal.html('<strong>FREE <a href="' + o.discount.href + '" title="' + o.discount.name + '">' + o.discount.name + '</a></strong><br/>Value &pound;' + o.discount.price);
                }
                else {
                    //% off
                    divDeal.html('<strong>' + o.discount.value + '% OFF <a href="' + o.discount.href + '" title="' + o.discount.name + '">' + o.discount.name + '</a></strong><br/>Value &pound;' + o.discount.price + ' Save &pound;' + o.discount.save);
                }
            }
            else if (o.discount.type == "MULTI") {
                //Multibuy - Show different messages depending on the visibilty of the price.
				if (o.price == "HIDE") {
					divDeal.html('<strong>MULTIBUY <a href="' + o.discount.href + '" title="MULTIBUY Click for price">Click for price</a></strong>');
				}
				else {
					if (o.price == 'titleist') {
						divDeal.html('<strong>MULTIBUY Available</strong>');
					}
					else {
						divDeal.html('<strong>MULTIBUY <a href="' + o.discount.href + '" title="MULTIBUY Buy ' + o.discount.value + ' for &pound;' + o.discount.price + '">Buy ' + o.discount.value + ' for &pound;' + o.discount.price + '</a></strong>');
					}
				}	
			}


            divDeal.css({ display: 'block' });
        }
        else {
            divDeal.html('');
            divDeal.css({ display: 'none' });
        }

        var divRating = $(target + '_Rating');          
        var divOOS = $(target + '_OOS');
        
        if (o.oos <= 0) {
            divRating.removeClass("norating");
            divRating.removeClass("rating");
            divRating.addClass("stockWarning");
            divRating.html('Out of Stock');
            
        } else {        
            if (o.rating > 0) {
                divRating.removeClass("norating");
                divRating.removeClass("rating");
                divRating.removeClass("stockWarning");
                divRating.addClass("rating");
                divRating.html('<div class="count" style="width:' + o.rating + 'px;"></div>');
            }
            else {
                divRating.removeClass("norating");
                divRating.removeClass("rating");
                divRating.removeClass("stockWarning");
                divRating.addClass("norating");
                divRating.html("<!-- -->");
            }        
        }
        
        //}
    }

    // PRODUCT HOVER FUNCTION
    var slightDelay;
    var dynamicClass;
	var objTopPad;
	var top;
	var left;
	
    var _attachProductHover = function() {
       $('.withHover').hoverIntent({
            sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
            interval: 200, // number = milliseconds for onMouseOver polling interval    
            timeout: 0, // number = milliseconds delay before onMouseOut    
            over: function() {
            	dynamicClass = ($(this).parents('div').attr('class') + 'Hover');
				var pos = $(this).offset();
				left = pos.left;
				top = pos.top;
				objTopPad = parseInt($(this).css("padding-top"));
				
				left -= 18;
				top -= (38 - objTopPad);
				
				// CONDITIONS FOR DIFFERENT SPACINGS INC. SIS'S
				if ($(this).hasClass('divide') && $(this).parents('div').hasClass('subCatGrid')) {
                	left = left + 11;
                }
				if ($(this).hasClass('divide') && $(this).parents('div').hasClass('subCatGrid') && $(this).parents('div').hasClass('nike')) {
                	left = left - 11;
                }
				if ($(this).hasClass('divide') && $(this).parents('div').hasClass('subCatGrid') && $(this).parents('div').hasClass('taylormade')) {
                	left = left - 10;
                }
				if ($(this).hasClass('divide') && $(this).parents('div').hasClass('subCatGrid') && $(this).parents('div').hasClass('cobra')) {
                	left = left - 11;
                }
                 
				$('.productPopupContainer').css({ left: left, top: top});
				var proddiv = $(this);
				MAD.products.showProduct(enlargeContID, proddiv, proddiv.attr('prod'));
				$('.productPopupContainer').mouseover()
            },
            out: function() {
                //
            }
        }); 
	}
	
	var _productPopupHover = function() {
        $('.productPopupContainer').hover(function(event) {
			$('.productPopup').addClass(dynamicClass);
			$('.productPopupContainer').show();
		}, function() {
		   	$('.productPopup').removeClass(dynamicClass);
    		$('.productPopupContainer').hide();
        });
  	}

    //return public methods
    return {
        addProduct: _addProduct,
        findProduct: _findProduct,
        Products: _Products,
        showProduct: _showProduct,
        attachProductHover: _attachProductHover,
		productPopupHover: _productPopupHover
    }

})();

//Namespace dummy object
MAD.entities = {};

//Class to represent a Product
MAD.entities.product = function(ID, Name, BrandName, Href, Image, CommercialMsg, Price, RRP, Save, Rating, Video, OOS, Discount) {
    this.id = ID;
    this.name = Name;
    this.brandName = BrandName;
    this.href = Href;
    this.image = Image;
    this.commercialMsg = CommercialMsg;
    this.price = Price;
    this.rrp = RRP;
    this.save = Save;
    this.rating = Rating;
    this.video = Video;
    this.oos = OOS;
    this.discount = Discount;    
};
MAD.entities.discount = function(Type, Value, Name, Price, Save, Href) {
    this.type = Type;
    this.value = Value;
    this.name = Name;
    this.price = Price;
    this.save = Save;
    this.href = Href;
};


//Namespace dummy object
MAD.pages = {};

//Pages Init Functions
MAD.pages.all = (function() {

    //Add product to collection
    var _init = function() {
        _flyouts();
        _newsletter();
        _toolbar();
        _searchDropDown();
        _navDelay();
		_carouselTips();
        //_impulseCarousel();
    }

    var _flyouts = function() {
        // PREFERENCE BAR FLYOUTS
        $("#header ul.preferences li a.expand").click(function(e) {
            e.preventDefault();
            var parentObj = $(this).parent();
            parentObj.find(".ieShim").slideToggle(); // IE6 IFRAME SHIM FIX

            // CALL TAB ON CALLBACK FOR SMOOTH ANIMATION
            if (parentObj.find(".expandedContent").is(":hidden")) {
                parentObj.find("a.expand").addClass("open");
                parentObj.find(".expandedContent").stop(true, true).slideDown('slow');
            }
            else {
                parentObj.find(".expandedContent").stop(true, true).slideUp('slow', function() {
                    parentObj.find("a.expand").removeClass("open");
                });
            }

            $("ul.preferences li a.expand").not(this).removeClass("open");
            $("ul.preferences li a.expand").not(".open").parent().find(".expandedContent").hide();
            $("ul.preferences li").not(parentObj).find(".ieShim").hide();
            return false;
        });

        // FLYOUT CLOSE
        $("#header ul.preferences li .expandedContent a.closeBox").click(function() {
            var closeObj = $(this).parent();
            closeObj.parent().find(".ieShim").hide();
            closeObj.slideUp('slow', function() {
                closeObj.parent().find("a.expand").removeClass("open");
            });
            return false;
        });
    }

    var _newsletter = function() {

        // EMAIL NEWSLETTER SIGNUP
        $(".newsletterEmail").focus(function() {
            $(this).val("");
        });

        $(".newsletterEmail").blur(function() {
            if ($(this).attr("value") == "") {
                $(this).val("--Enter Email Address--");
            }
        });
    }

    var _toolbar = function() {
        // FLOATING TOOLBAR

        if ($.cookie("ftbState") == "closed") {
            $(".toolbarContainer ul.tbSlide").hide();
            $(".toolbar .tbToggle").addClass("closed");
        }
        $(".toolbarContainer").show();

        $(".toolbar a.expBtn").click(function() {
            var self = $(this).parent().find(".expWrap");
            $(".toolbar .expWrap").not(self).slideUp();
            $(this).parent().find(".expWrap").stop(true, true).slideToggle();

            if ($(this).hasClass('facebook')) {
                var $fb = $('<iframe src="http://www.facebook.com/plugins/likebox.php?id=18727097221&amp;width=402&amp;connections=7&amp;stream=true&amp;header=false&amp;height=480" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:402px; height:480px;" allowTransparency="true"></iframe>');
                $(this).parent().find('.inner .content').html($fb);
            }
            return false;
        });

        $(".toolbar .tbToggle").click(function() {
            $(".toolbar ul").animate({ width: 'toggle' });
            $(this).toggleClass("closed");
            if ($(this).hasClass("closed")) {
                $.cookie("ftbState", "closed"); // PLACE COOKIE
            }
            else {
                $.cookie("ftbState", null); // DELETE COOKIE
            }
            return false;
        });

        $(".toolbar .expWrap .close").click(function() {
            $(this).parents(".expWrap").slideToggle();
            return false;
        });
		
		if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
		   	$(".toolbarContainer").css("position", "static");
		};
    }

    var _searchDropDown = function() {
        // SEARCH DROPDOWN HOVER
        $("#searchDropDown .product").live("mouseover mouseout", function() {
            $(this).toggleClass("hovered");
        });
    }

    var _impulseCarousel = function() {
        for (i = 1; i <= 2; i++) {
            if ($(".ImpCarousel" + i).length) {
                $(".ImpCarousel" + i + " .impulseCarousel").jCarouselLite({
                    btnNext: ".ImpCarousel" + i + " #next",
                    btnPrev: ".ImpCarousel" + i + " #prev",
                    visible: 1,
                    //scroll: 1,
                    circular: false
                });
            }
        }
        if ($(".ImpCarousel1").length) {
            $(".ImpCarousel2").hide();
        }
    }


    var _navDelay = function() {
        $(".topLevel > li").hoverIntent({
            sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
            interval: 200, // number = milliseconds for onMouseOver polling interval    
            timeout: 0, // number = milliseconds delay before onMouseOut    
            over: function() {
                $(this).addClass("open");
            },
            out: function() {
                $(this).removeClass("open");
            }
        });
    }

	var _carouselTips = function() {
		$('.control').hover(function() {
			if (!$(this).hasClass("disabled")) {
				$(this).find('.carouselTip').stop(false,true).fadeIn(300);
			}
		},
  		function () {
			$(this).find('.carouselTip').stop(false,true).fadeOut(300);
		});	
	}


    var _IE6 = function() {
          $(window).scroll(function() {
            $('.toolbarContainer').stop().animate({ top: ($(window).height() + $(document).scrollTop() - 42) }, 0, 'linear');
        });
    }

    //return public methods
    return {
        init: _init,
        navDelay: _navDelay,
        impulseCarousel: _impulseCarousel,
		carouselTips: _carouselTips,
        IE6: _IE6
    }
})();


//Pages Init Functions
MAD.pages.home = (function() {

    var _init = function() {
        _saleCarousel();
    }

    var _saleCarousel = function() {
        for (i = 1; i <= 5; i++) {
            if ($(".Carousel" + i).length > 0) {
                $(".Carousel" + i + " .saleItemsCarousel").jCarouselLite({
                    btnNext: ".Carousel" + i + " .next" + i,
                    btnPrev: ".Carousel" + i + " .prev" + i,
                    visible: 1,
                    scroll: 1,
                    circular: false
                });
            } 	   
		}
		
    }

    //return public methods
    return {
        init: _init
    }
})();

//Pages Init Functions
//MAD.pages.product = (function() {
//
//    //Add product to collection
//    var _init = function() {
//
//    }
//
//    //return public methods
//    return {
//        init: _init
//    }
//})();